<?php

namespace app\admin\controller\lift;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\model\user\User;
use think\Db;

/**
 * 电梯管理
 *
 * @icon fa fa-user
 */
class Lift extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['getSaleMan'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Lift');
       // $this->view->assign('getRejuctTypeList', $this->model->getRejuctTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch =true;
        $this->searchFields = 'proprietor_name,phone,address,elevator_no';
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $count = $this->model
               // ->with(['saleman'])
                ->where($where)
                ->count();
            $list = $this->model
              //  ->with(['saleman'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            foreach ($list as $w=>&$v){
               // $v->getRelation('saleman')->visible(['real_name']);
            }
            $sql = $this->model->getLastSql();
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
//            $params['create_time'] = time();
//            $params['admin_id'] = $this->auth->id;
//            $image_arr = explode('aliyuncs.com',$params['logo']);
//            if($params['logo']){
//                $params['logo'] = $image_arr[1];
//            }
//            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
//            $randStr = str_shuffle($str);
//            $rands = substr($randStr, 0, 6);
//            $params['code'] = $rands;
            $params['buildings'] = $params['buildings'] . '-' . $params['unit'];
            $user = Db::name('user')->where(['phone' => $params['phone']])->find();
            $params['uid'] = $user['uid'];
            $params['source'] = '3';
            $res = $this->model->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
                    $image_arr = explode('aliyuncs.com',$params['logo']);
                    if($params['logo']){
                        $params['logo'] = $image_arr[1];
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['logo']){
            $row['logo'] = 'https://yunwotuojiao.oss-cn-fuzhou.aliyuncs.com'.$row['logo'];
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id'=>$row['id']])->delete();
        $this->success();
    }

    /**
     * 详情
     */
    public function detail($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
                    $image_arr = explode('aliyuncs.com',$params['logo']);
                    if($params['logo']){
                        $params['logo'] = $image_arr[1];
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['check_time'] >0){
            $row['check_time'] = date('Y-m-d H:i:s',$row['check_time']);
        }
        if($row['submit_check_time'] >0){
            $row['submit_check_time'] = date('Y-m-d H:i:s',$row['submit_check_time']);
        }
        if($row['add_time'] >0){
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
        }
        if($row['clean_area'] == 1){
            $row['clean_area_text'] = '轿厢内部四个面';
        }else if($row['clean_area'] == 2){
            $row['clean_area_text'] = '轿厢内部四个面+地板+厅门';
        }
        if($row['remark_type'] == 1){
            $row['remark_type_text'] = '电梯使用标识不清晰';
        }else if($row['remark_type'] == 2){
            $row['remark_type_text'] = '联系电话联系不上';
        }else if($row['remark_type'] == 3){
            $row['remark_type_text'] = '电梯非加装电梯';
        }else if($row['remark_type'] == 4){
            $row['remark_type_text'] = '地址填写错误';
        }else if($row['remark_type'] == 5){
            $row['remark_type_text'] = '地址不在三环内';
        }
        if($row['is_can_update'] == 1){
            $row['is_can_update_text'] = '是';
        }else if($row['is_can_update'] == 0){
            $row['is_can_update_text'] = '否';
        }
        $row['salesman'] = Db::name('user')->where(['uid'=>$row['salesman_id']])->value('real_name');
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function audit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    if($params['remark_type'] == 1){
                        $params['remark'] = '电梯使用标识不清晰';
                    }else if($params['remark_type'] == 2){
                        $params['remark'] = '联系电话联系不上';
                    }else if($params['remark_type'] == 3){
                        $params['remark'] = '电梯非加装电梯';
                    }else if($params['remark_type'] == 4){
                        $params['remark'] = '地址填写错误';
                    }else if($params['remark_type'] == 5){
                        $params['remark'] = '地址不在三环内';
                    }
                    $row['status'] = 3;
                    var_dump();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['check_time'] >0){
            $row['check_time'] = date('Y-m-d H:i:s',$row['check_time']);
        }else{
            $row['check_time'] = '-';
        }
        if($row['submit_check_time'] >0){
            $row['submit_check_time'] = date('Y-m-d H:i:s',$row['submit_check_time']);
        }else{
            $row['submit_check_time'] = '-';
        }
        if($row['add_time'] >0){
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
        }
        if($row['clean_area'] == 1){
            $row['clean_area_text'] = '轿厢内部四个面';
        }else if($row['clean_area'] == 2){
            $row['clean_area_text'] = '轿厢内部四个面+地板+厅门';
        }
        if($row['remark_type'] == 1){
            $row['remark_type_text'] = '电梯使用标识不清晰';
        }else if($row['remark_type'] == 2){
            $row['remark_type_text'] = '联系电话联系不上';
        }else if($row['remark_type'] == 3){
            $row['remark_type_text'] = '电梯非加装电梯';
        }else if($row['remark_type'] == 4){
            $row['remark_type_text'] = '地址填写错误';
        }else if($row['remark_type'] == 5){
            $row['remark_type_text'] = '地址不在三环内';
        }
        if($row['is_can_update'] == 1){
            $row['is_can_update_text'] = '是';
        }else if($row['is_can_update'] == 0){
            $row['is_can_update_text'] = '否';
        }
        $row['salesman'] = Db::name('user')->where(['uid'=>$row['salesman_id']])->value('real_name');
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function do_assign($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['check_time'] >0){
            $row['check_time'] = date('Y-m-d H:i:s',$row['check_time']);
        }
        if($row['submit_check_time'] >0){
            $row['submit_check_time'] = date('Y-m-d H:i:s',$row['submit_check_time']);
        }
        if($row['add_time'] >0){
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
        }
        if($row['clean_area'] == 1){
            $row['clean_area_text'] = '轿厢内部四个面';
        }else if($row['clean_area'] == 2){
            $row['clean_area_text'] = '轿厢内部四个面+地板+厅门';
        }
        if($row['remark_type'] == 1){
            $row['remark_type_text'] = '电梯使用标识不清晰';
        }else if($row['remark_type'] == 2){
            $row['remark_type_text'] = '联系电话联系不上';
        }else if($row['remark_type'] == 3){
            $row['remark_type_text'] = '电梯非加装电梯';
        }else if($row['remark_type'] == 4){
            $row['remark_type_text'] = '地址填写错误';
        }else if($row['remark_type'] == 5){
            $row['remark_type_text'] = '地址不在三环内';
        }
        if($row['is_can_update'] == 1){
            $row['is_can_update_text'] = '是';
        }else if($row['is_can_update'] == 0){
            $row['is_can_update_text'] = '否';
        }
        $row['salesman'] = Db::name('user')->where(['uid'=>$row['salesman_id']])->value('real_name');
        $row['is_have_saleman'] = 0;
        if($row['saleman']){
            $row['is_have_saleman'] = 1;
        }
        $this->view->assign("row", $row);
        $this->assignconfig("is_have_saleman", $row['is_have_saleman']);
        return $this->view->fetch();
    }

    /**
     * 获取业务列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSaleMan()
    {
        $keValue = $this->request->request("keyValue");
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $show_province_id = [];
            $new_where = [
                //'class_status'=>0
            ];
            if ($keValue) {
                $keValue = explode(',', $keValue);
                // $new_arr = array_merge($keValue,$show_province_id);
                $new_where = [
                    'id' => ['in', $keValue]
                ];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = Db::name('user')
                ->where($where)
                ->where(['is_promoter'=>1])
                ->where($new_where)
                ->count();

            $list =Db::name('user')
                ->where($where)
                ->where(['is_promoter'=>1])
                ->where($new_where)
                ->order('uid desc')
                ->select();
            $sql = Db::name('user')->getLastSql();
            $list = collection($list)->toArray();
            $new_list = [];
            foreach ($list as $w => $v) {
                $new_data = [
                    'id' => $v['uid'],
//                    'province_id' => $v['province_id'],
                    'title' => $v['real_name'],
                ];
                $new_list[$w] = $new_data;
            }
            $result = array("total" => $total, "list" => $new_list,"sql"=>$sql);
            return json($result);
        }
    }


    /**
     * 详情
     */
    public function do_most_assign($ids=''){
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $check_id = $this->request->get("check_id");
            if ($params) {
                try {
                    $check_id_arr = explode(',',$check_id);
                    if(count($check_id)==0){
                        $this->error('尚未选择任何一笔订单');
                    }
                    $params['up_time'] = time();
                   // $params['salesman_id'] = time();
                    $result =  $this->model->where(['id'=>['in',$check_id_arr],'salesman_id'=>0])->update($params);
                    if ($result !== false) {
                        $this->success();
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 切换
     */
    public function change($ids = '')
    {
       $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update_data = [];
        if($row['examine']==1){
            $update_data['examine'] = 2;
        }else if($row['examine']==2){
            $update_data['examine'] = 1;
        }
        $res = $this->model->where(['id'=>$row['id']])->update($update_data);

        $this->success("切换成功");
    }

}
